var params = {
    "rows": 10, //设置每一页的条目数
    "page": 1, //设置当前的页码
    "maxpages": 5, //设置最多显示的页码数
    /** 接口自带参数 */
    "no": "",
    "name": "",
    "sex": ""
};

/**
 * 调用接口获取学生数据
 */
function init() {
    params.rows = parseInt($('#pagesize').val());
    params.no = $('#txtno').val();
    params.name = $('#txtname').val();
    jqPagingInitLogin('/studentlist', params, 'divpage', 'settable');
}

/**
 * 绘制表格数据
 * @param obj
 * @returns {boolean}
 */
function settable(obj) {
    var noticeHtml = '';
    if (obj.table.length == 0) {
        noticeHtml += '<tr>';
        noticeHtml += '<td colspan="8">未检索到任何记录</td>';
        noticeHtml += '</tr>';
        $("#tbody").html(noticeHtml);
        return false;
    }
    for (var i = 0; i < obj.table.length; i++) {
        let student = obj.table[i];
        let id = student.id;
        let no = student.student_no;
        let sex = student.student_sex;
        let name = student.student_name;
        let birth = student.student_birth;
        let grade = student.grade == null || student.grade == undefined ? "" : student.grade;
        let className = student.className == null || student.className == undefined ? "" : student.grade;
        let email = student.student_email;
        let desc = student.student_desc;
        noticeHtml += `<tr>
                        <td><input type="checkbox" class="checkbox" value="${id}"/></td>
                        <td name="no">${no}</td>
                        <td name="name">${name}</td>
                        <td name="sex">${sex == '1' ? '男' : '女'}</td>
                        <td name="birth">${birth}</td>
                        <td name="grade">${grade}</td>
                        <td name="class">${className}</td>
                        <td name="email">${email}</td>
                        <td name="desc">${desc}</td>
                        <td><button class="btn btn-link" onclick="update('${id}')">编辑</button></td>
                    </tr>`;
    }
    $("#tbody").html(noticeHtml);
    $('input').iCheck({
        checkboxClass: 'icheckbox_square-red',
        radioClass: 'iradio_square-red',
        increaseArea: '20%' // optional
    });
}

/**
 * 弹出添加用户信息框
 */
function addUser() {
    layer.open({
        type: 1,
        title: '新增学生信息',
        closeBtn: 1, //显示关闭按钮
        shadeClose: false,
        area: ['893px', '600px'],
        cancel: function () {
            //不管是新增还是更新后都清空表单
            $("#no").val('');
            $("#name").val('');
            $("input[name='sex'][value='男']").iCheck('check');
            $("#desc").val('');
            $("#email").val('');
            $("#birth").val('');
            $("#hidNo").val('');
            isUpdate = false;
        },
        content: $("#div_add")
    });
}

/***
 * 删除用户信息
 */
function deleteUser() {
    if ($("input[type='checkbox'][id!='checkAll']:checked").length === 0) {
        layer.msg('请至少选择一个学生进行删除', {icon: 2, time: 2000});
        return false;
    }
    layer.confirm('确认要删除这些学生吗？', {
        btn: ['是', '否'] //按钮
    }, function () {
        let id = "";
        $("input[type='checkbox'][id!='checkAll']:checked").each(function () {
            id += $(this).val() + ",";
        });
        id = id.substr(0, id.length - 1);
        var data = {
            id: id
        }
        var result = ApiPostLogin('/deletestudent', JsonToStr(data));
        if (result != -1) {
            console.log(result);
            var obj = eval('(' + result + ')');
            if (obj.error == "1") {
                layer.msg('删除成功', {icon: 1, time: 2000}, function () {
                    init();
                    layer.closeAll();
                });
            } else {
                layer.msg(obj.msg, function () {
                    init();
                    layer.closeAll();
                });
            }
        }
    }, function () {
    });

}

/**
 * 是否是更新状态
 */
var isUpdate = false;

/**
 * 弹出更新用户框
 * @param {学生ID} no
 */
function update(id) {
    $("#hidNo").val(id);
    isUpdate = true;
    let flag = initData();
    if (flag) {
        layer.open({
            type: 1,
            title: '修改学生信息',
            closeBtn: 1, //显示关闭按钮
            shadeClose: false,
            area: ['893px', '600px'],
            cancel: function () {
                //不管是新增还是更新后都清空表单
                $("#no").val('');
                $("#name").val('');
                $("input[name='sex'][value='男']").iCheck('check');
                $("#desc").val('');
                $("#email").val('');
                $("#birth").val('');
                $("#hidNo").val('');
                isUpdate = false;
            },
            content: $("#div_add")
        });
    } else {
        layer.msg('该学生不存在', {icon: 2, time: 2000});
    }
}

/**
 * 加载一条用户数据
 */
function initData() {
    let exists = false;
    let id = $("#hidNo").val();
    var data = {
        id: id
    }
    var result = ApiPostLogin('/getstudent', JsonToStr(data));
    if (result != -1) {
        console.log(result);
        var obj = eval('(' + result + ')');
        if (obj.error == "1") {
            exists = true;
            let data = obj.data;
            $("#no").val(data.student_no);
            $("#no").attr("readonly", true);

            $("#name").val(data.student_name);
            $("input[name='sex'][value='" + data.student_sex + "']").iCheck('check');
            $("#birth").val(data.student_birth);
            $("#email").val(data.student_email);
            $("#desc").val(data.student_desc);
        } else {
            layer.msg('失败');
        }
    }
    return exists;
}

/**
 * 提交数据
 */
function submit() {
    let no = $("#no").val();
    if (no.trim() === "") {
        layer.msg('学号不能为空', {icon: 2, time: 2000});
        $("#no").focus();
        return false;
    }
    let name = $("#name").val();
    if (name.trim() === "") {
        layer.msg('学生名不能为空', {icon: 2, time: 2000});
        $("#name").focus();
        return false;
    }
    let sex = $("input[name='sex']:checked").val();
    let birth = $("#birth").val();
    if (birth.trim() === "") {
        layer.msg('出生年月不能为空', {icon: 2, time: 2000});
        $("#birth").focus();
        return false;
    }
    let email = $("#email").val();
    let desc = $("#desc").val();

    /**
     * 更新状态只需要更新表格内数据
     */
    if (isUpdate) {
        var data = {
            id: $("#hidNo").val(),
            no: no,
            name: name,
            sex: sex,
            birth: birth,
            email: email,
            desc: desc
        }
        var result = ApiPostLogin('/updatestudent', JsonToStr(data));
        if (result != -1) {
            console.log(result);
            var obj = eval('(' + result + ')');
            if (obj.error == "1") {
                layer.msg('更新成功', {icon: 1, time: 2000}, function () {
                    init();
                    layer.closeAll();
                });
            } else {
                layer.msg('失败');
            }
        }
    } else {
        var data = {
            no: no,
            name: name,
            sex: sex,
            birth: birth,
            email: email,
            desc: desc
        }
        var result = ApiPostLogin('/addstudent', JsonToStr(data));
        if (result != -1) {
            console.log(result);
            var obj = eval('(' + result + ')');
            if (obj.error == "1") {

                layer.msg('新增成功', {icon: 1, time: 2000}, function () {
                    init();
                    layer.closeAll();
                });
            } else {
                layer.msg('失败');
            }
        }
    }
    //不管是新增还是更新后都清空表单
    $("#no").val('');
    $("#name").val('');
    $("input[name='sex'][value='男']").iCheck('check');
    $("#desc").val('');
    $("#email").val('');
    $("#birth").val('');
    $("#hidNo").val('');
    isUpdate = false;
}

$(function () {
    init();
    /**
     * 绑定checkbox和radio的样式
     */
    $('input').iCheck({
        checkboxClass: 'icheckbox_square-red',
        radioClass: 'iradio_square-red',
        increaseArea: '20%' // optional
    });
    /**
     * 绑定新增按钮事件
     */
    $("#btnAdd").click(function () {
        addUser();
    });
    /**
     * 绑定删除按钮事件方法
     */
    $("#btnDel").click(function () {
        deleteUser();
    });
    /**
     * 绑定查询按钮事件方法
     */
    $("#btnQuery").click(function () {
        init();
    });
    /**
     * 绑定提交按钮事件方法
     */
    $("#btn_submit").click(function () {
        submit();
    });
    /**
     * 全选按钮，全选
     */
    $("#checkAll").on('ifChecked', function (event) {
        $("input[type='checkbox'][id!='checkAll']").iCheck('check');
    });
    /**
     * 全选取消
     */
    $("#checkAll").on('ifUnchecked', function (event) {
        $("input[type='checkbox'][id!='checkAll']").iCheck('uncheck');
    });

});